﻿using YooAssetsSystem.Fsm;
using UnityEngine;
using YooAsset;

namespace YooAssetsSystem.Patch
{
	/// <summary>
	/// 创建下载器 通知是否需要下载 4
	/// </summary>
	public class CreateDownloadNode : BasePatchNode
	{
		public override void OnEnter()
		{
			var patchConfig = Owner.Config;
			var tags = patchConfig.loadTags;
			var multiMaxNumber = patchConfig.multiMaxNumber;
			var failedTryAgain = patchConfig.failedTryAgain;

			ResourceDownloaderOperation downloader = null;
			if (tags.Length == 0)
			{
				downloader = YooAssets.GetPackage(Owner.Package)
					.CreateResourceDownloader(multiMaxNumber, failedTryAgain);
			}
			else
			{
				downloader = YooAssets.GetPackage(Owner.Package)
					.CreateResourceDownloader(tags, multiMaxNumber, failedTryAgain);
			}

			if (downloader.TotalDownloadCount == 0)
			{
				//清理缓存
				var package = YooAssets.GetPackage(shareData.package);
				var operation = package.UnloadUnusedAssetsAsync();
				operation.Completed += delegate(AsyncOperationBase operationBase)
				{
					machine.ChangeState<PatchDoneNode>();
				};
			}
			else
			{
				Debug.Log($"总共{downloader.TotalDownloadCount}个资源需要下载 ！");
				//todo: 检查磁盘大小...

				shareData.downloader = downloader;
				var totalDownloadCount = downloader.TotalDownloadCount;
				var totalDownloadBytes = downloader.TotalDownloadBytes;
				Owner.Event.NeedDownloadEvent?.Invoke(totalDownloadCount, totalDownloadBytes,
					delegate { machine.ChangeState<DownloadFilesNode>(); });
			}
		}

		public override void OnExit()
		{
			base.OnExit();
		}
	}
}
